package zsc.ruanc.practicaltraining.security.auth;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import zsc.ruanc.practicaltraining.mapper.UserMapper;
import zsc.ruanc.practicaltraining.model.domain.TUser;
import zsc.ruanc.practicaltraining.service.UserService;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     *  查询用户名字、密码、身份 就这样要求
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        TUser user = userMapper.selectByName(username);
        AuthUser authUser = new AuthUser();

        if (user == null) {

            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        } else if (user.getValid() == false) {
            throw new LockedException(String.format("%s.该用户账号被封锁", username));
        } else {

            authUser.setUsername(user.getUsername());
            authUser.setPassword(user.getPassword());
            authUser.setId(user.getId());

            int x = user.getValid() == true ? 0 : 1;
            authUser.setState(x);

            String role = user.getRoleId() == 1 ? "ROLE_admin" : "ROLE_common";

            authUser.setRole(role);

            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            authorityList.add(new SimpleGrantedAuthority(role));

            System.out.println("loadUserByUsername......user ===> " + user);

        }
        return authUser;

    }
}
